{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp models.deepnpts"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# DeepNPTS"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Deep Non-Parametric Time Series Forecaster (`DeepNPTS`) is a non-parametric baseline model for time-series forecasting. This model generates predictions by sampling from the empirical distribution according to a tunable strategy. This strategy is learned by exploiting the information across multiple related time series. This model provides a strong, simple baseline for time series forecasting. \n",
    "\n",
    "\n",
    "**References**<br>\n",
    "[Rangapuram, Syama Sundar, Jan Gasthaus, Lorenzo Stella, Valentin Flunkert, David Salinas, Yuyang Wang, and Tim Januschowski (2023). \"Deep Non-Parametric Time Series Forecaster\". arXiv.](https://arxiv.org/abs/2312.14657)<br>\n",
    "\n",
    "\n",
    ":::{.callout-warning collapse=\"false\"}\n",
    "#### Losses\n",
    "\n",
    "This implementation differs from the original work in that a weighted sum of the empirical distribution is returned as forecast. Therefore, it only supports point losses.\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import neuralforecast.losses.pytorch as losses\n",
    "from typing import Optional\n",
    "\n",
    "\n",
    "from neuralforecast.common._base_model import BaseModel\n",
    "from neuralforecast.losses.pytorch import MAE\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import logging\n",
    "import warnings\n",
    "\n",
    "from fastcore.test import test_eq\n",
    "from nbdev.showdoc import show_doc\n",
    "from neuralforecast.common._model_checks import check_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "logging.getLogger(\"pytorch_lightning\").setLevel(logging.ERROR)\n",
    "logging.getLogger(\"lightning_fabric\").setLevel(logging.ERROR)\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class DeepNPTS(BaseModel):\n",
    "    \"\"\" DeepNPTS\n",
    "\n",
    "    Deep Non-Parametric Time Series Forecaster (`DeepNPTS`) is a baseline model for time-series forecasting. This model generates predictions by (weighted) sampling from the empirical distribution according to a learnable strategy. The strategy is learned by exploiting the information across multiple related time series.\n",
    "\n",
    "    **Parameters:**<br>\n",
    "    `h`: int, Forecast horizon. <br>\n",
    "    `input_size`: int, autorregresive inputs size, y=[1,2,3,4] input_size=2 -> y_[t-2:t]=[1,2].<br>\n",
    "    `hidden_size`: int=32, hidden size of dense layers.<br>\n",
    "    `batch_norm`: bool=True, if True, applies Batch Normalization after each dense layer in the network.<br>\n",
    "    `dropout`: float=0.1, dropout.<br>\n",
    "    `n_layers`: int=2, number of dense layers.<br>\n",
    "    `stat_exog_list`: str list, static exogenous columns.<br>\n",
    "    `hist_exog_list`: str list, historic exogenous columns.<br>\n",
    "    `futr_exog_list`: str list, future exogenous columns.<br>\n",
    "    `exclude_insample_y`: bool=False, the model skips the autoregressive features y[t-input_size:t] if True.<br>\n",
    "    `loss`: PyTorch module, instantiated train loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `valid_loss`: PyTorch module=`loss`, instantiated valid loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `max_steps`: int=1000, maximum number of training steps.<br>\n",
    "    `learning_rate`: float=1e-3, Learning rate between (0, 1).<br>\n",
    "    `num_lr_decays`: int=-1, Number of learning rate decays, evenly distributed across max_steps.<br>\n",
    "    `early_stop_patience_steps`: int=-1, Number of validation iterations before early stopping.<br>\n",
    "    `val_check_steps`: int=100, Number of training steps between every validation loss check.<br>\n",
    "    `batch_size`: int=32, number of different series in each batch.<br>\n",
    "    `valid_batch_size`: int=None, number of different series in each validation and test batch, if None uses batch_size.<br>\n",
    "    `windows_batch_size`: int=1024, number of windows to sample in each training batch, default uses all.<br>\n",
    "    `inference_windows_batch_size`: int=-1, number of windows to sample in each inference batch, -1 uses all.<br>\n",
    "    `start_padding_enabled`: bool=False, if True, the model will pad the time series with zeros at the beginning, by input size.<br>\n",
    "    `step_size`: int=1, step size between each window of temporal data.<br>\n",
    "    `scaler_type`: str='identity', type of scaler for temporal inputs normalization see [temporal scalers](https://nixtla.github.io/neuralforecast/common.scalers.html).<br>\n",
    "    `random_seed`: int, random_seed for pytorch initializer and numpy generators.<br>\n",
    "    `drop_last_loader`: bool=False, if True `TimeSeriesDataLoader` drops last non-full batch.<br>\n",
    "    `alias`: str, optional,  Custom name of the model.<br>\n",
    "    `optimizer`: Subclass of 'torch.optim.Optimizer', optional, user specified optimizer instead of the default choice (Adam).<br>\n",
    "    `optimizer_kwargs`: dict, optional, list of parameters used by the user specified `optimizer`.<br>\n",
    "    `lr_scheduler`: Subclass of 'torch.optim.lr_scheduler.LRScheduler', optional, user specified lr_scheduler instead of the default choice (StepLR).<br>\n",
    "    `lr_scheduler_kwargs`: dict, optional, list of parameters used by the user specified `lr_scheduler`.<br>\n",
    "    `dataloader_kwargs`: dict, optional, list of parameters passed into the PyTorch Lightning dataloader by the `TimeSeriesDataLoader`. <br>\n",
    "    `**trainer_kwargs`: int,  keyword trainer arguments inherited from [PyTorch Lighning's trainer](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.trainer.trainer.Trainer.html?highlight=trainer).<br>    \n",
    "\n",
    "    **References**<br>\n",
    "    - [Rangapuram, Syama Sundar, Jan Gasthaus, Lorenzo Stella, Valentin Flunkert, David Salinas, Yuyang Wang, and Tim Januschowski (2023). \"Deep Non-Parametric Time Series Forecaster\". arXiv.](https://arxiv.org/abs/2312.14657)<br>\n",
    "\n",
    "    \"\"\"\n",
    "    # Class attributes\n",
    "    EXOGENOUS_FUTR = True\n",
    "    EXOGENOUS_HIST = True\n",
    "    EXOGENOUS_STAT = True\n",
    "    MULTIVARIATE = False    # If the model produces multivariate forecasts (True) or univariate (False)\n",
    "    RECURRENT = False       # If the model produces forecasts recursively (True) or direct (False)\n",
    "    \n",
    "    def __init__(self,\n",
    "                 h,\n",
    "                 input_size: int,\n",
    "                 hidden_size: int = 32,\n",
    "                 batch_norm: bool = True,\n",
    "                 dropout: float = 0.1,\n",
    "                 n_layers: int = 2,\n",
    "                 stat_exog_list = None,\n",
    "                 hist_exog_list = None,\n",
    "                 futr_exog_list = None,\n",
    "                 exclude_insample_y = False,\n",
    "                 loss = MAE(),\n",
    "                 valid_loss = MAE(),\n",
    "                 max_steps: int = 1000,\n",
    "                 learning_rate: float = 1e-3,\n",
    "                 num_lr_decays: int = 3,\n",
    "                 early_stop_patience_steps: int =-1,\n",
    "                 val_check_steps: int = 100,\n",
    "                 batch_size: int = 32,\n",
    "                 valid_batch_size: Optional[int] = None,\n",
    "                 windows_batch_size: int = 1024,\n",
    "                 inference_windows_batch_size: int = 1024,\n",
    "                 start_padding_enabled = False,\n",
    "                 step_size: int = 1,\n",
    "                 scaler_type: str = 'standard',\n",
    "                 random_seed: int = 1,\n",
    "                 drop_last_loader = False,\n",
    "                 alias: Optional[str] = None,\n",
    "                 optimizer = None,\n",
    "                 optimizer_kwargs = None,\n",
    "                 lr_scheduler = None,\n",
    "                 lr_scheduler_kwargs = None,\n",
    "                 dataloader_kwargs = None,\n",
    "                 **trainer_kwargs):\n",
    "\n",
    "        if exclude_insample_y:\n",
    "            raise Exception('DeepNPTS has no possibility for excluding y.')\n",
    "\n",
    "        if loss.outputsize_multiplier > 1:\n",
    "            raise Exception('DeepNPTS only supports point loss functions (MAE, MSE, etc) as loss function.')               \n",
    "    \n",
    "        if valid_loss is not None and not isinstance(valid_loss, losses.BasePointLoss):\n",
    "            raise Exception('DeepNPTS only supports point loss functions (MAE, MSE, etc) as valid loss function.')   \n",
    "            \n",
    "        # Inherit BaseWindows class\n",
    "        super(DeepNPTS, self).__init__(h=h,\n",
    "                                    input_size=input_size,\n",
    "                                    stat_exog_list=stat_exog_list,\n",
    "                                    hist_exog_list=hist_exog_list,\n",
    "                                    futr_exog_list=futr_exog_list,\n",
    "                                    exclude_insample_y = exclude_insample_y,\n",
    "                                    loss=loss,\n",
    "                                    valid_loss=valid_loss,\n",
    "                                    max_steps=max_steps,\n",
    "                                    learning_rate=learning_rate,\n",
    "                                    num_lr_decays=num_lr_decays,\n",
    "                                    early_stop_patience_steps=early_stop_patience_steps,\n",
    "                                    val_check_steps=val_check_steps,\n",
    "                                    batch_size=batch_size,\n",
    "                                    valid_batch_size=valid_batch_size,\n",
    "                                    windows_batch_size=windows_batch_size,\n",
    "                                    inference_windows_batch_size=inference_windows_batch_size,\n",
    "                                    start_padding_enabled=start_padding_enabled,\n",
    "                                    step_size=step_size,\n",
    "                                    scaler_type=scaler_type,\n",
    "                                    random_seed=random_seed,\n",
    "                                    drop_last_loader=drop_last_loader,\n",
    "                                    alias=alias,\n",
    "                                    optimizer=optimizer,\n",
    "                                    optimizer_kwargs=optimizer_kwargs,\n",
    "                                    lr_scheduler=lr_scheduler,\n",
    "                                    lr_scheduler_kwargs=lr_scheduler_kwargs,\n",
    "                                    dataloader_kwargs=dataloader_kwargs,\n",
    "                                    **trainer_kwargs)\n",
    "\n",
    "        self.h = h\n",
    "        self.hidden_size = hidden_size\n",
    "        self.dropout = dropout\n",
    "\n",
    "        input_dim = input_size * (1 + self.futr_exog_size + self.hist_exog_size) + self.stat_exog_size + self.h * self.futr_exog_size\n",
    "        \n",
    "        # Create DeepNPTSNetwork\n",
    "        modules = []       \n",
    "        for i in range(n_layers):\n",
    "            modules.append(nn.Linear(input_dim if i == 0 else hidden_size, hidden_size))\n",
    "            modules.append(nn.ReLU())\n",
    "            if batch_norm:\n",
    "                modules.append(nn.BatchNorm1d(hidden_size))\n",
    "            if dropout > 0.0:\n",
    "                modules.append(nn.Dropout(dropout))\n",
    "\n",
    "        modules.append(nn.Linear(hidden_size, input_size * self.h))\n",
    "        self.deepnptsnetwork = nn.Sequential(*modules)\n",
    "\n",
    "    def forward(self, windows_batch):\n",
    "        # Parse windows_batch\n",
    "        x             = windows_batch['insample_y']                     #   [B, L, 1]\n",
    "        hist_exog     = windows_batch['hist_exog']                      #   [B, L, X]\n",
    "        futr_exog     = windows_batch['futr_exog']                      #   [B, L + h, F]\n",
    "        stat_exog     = windows_batch['stat_exog']                      #   [B, S]\n",
    "\n",
    "        batch_size, seq_len = x.shape[:2]                               #   B = batch_size, L = seq_len\n",
    "        insample_y = windows_batch['insample_y'] \n",
    "        \n",
    "        # Concatenate x_t with future exogenous of input\n",
    "        if self.futr_exog_size > 0:      \n",
    "            x = torch.cat((x, futr_exog[:, :seq_len]), dim=2)           #   [B, L, 1] + [B, L, F] -> [B, L, 1 + F]            \n",
    "        \n",
    "        # Concatenate x_t with historic exogenous\n",
    "        if self.hist_exog_size > 0:      \n",
    "            x = torch.cat((x, hist_exog), dim=2)                        #   [B, L, 1 + F] + [B, L, X] -> [B, L, 1 + F + X]            \n",
    "\n",
    "        x = x.reshape(batch_size, -1)                                   #   [B, L, 1 + F + X] -> [B, L * (1 + F + X)]\n",
    "\n",
    "        # Concatenate x with static exogenous\n",
    "        if self.stat_exog_size > 0:\n",
    "            x = torch.cat((x, stat_exog), dim=1)                        #   [B, L * (1 + F + X)] + [B, S] -> [B, L * (1 + F + X) + S]\n",
    "\n",
    "        # Concatenate x_t with future exogenous of horizon\n",
    "        if self.futr_exog_size > 0:\n",
    "            futr_exog = futr_exog[:, seq_len:]                          #   [B, L + h, F] -> [B, h, F]\n",
    "            futr_exog = futr_exog.reshape(batch_size, -1)               #   [B, L + h, F] -> [B, h * F]\n",
    "            x = torch.cat((x, futr_exog), dim=1)                        #   [B, L * (1 + F + X) + S] + [B, h * F] -> [B, L * (1 + F + X) + S + h * F]            \n",
    "\n",
    "        # Run through DeepNPTSNetwork\n",
    "        weights = self.deepnptsnetwork(x)                               #   [B, L * (1 + F + X) + S + h * F]  -> [B, L * h]\n",
    "\n",
    "        # Apply softmax for weighted input predictions\n",
    "        weights = weights.reshape(batch_size, seq_len, -1)              #   [B, L * h] -> [B, L, h]\n",
    "        x = F.softmax(weights, dim=1) * insample_y                      #   [B, L, h] * [B, L, 1] = [B, L, h]\n",
    "        forecast = torch.sum(x, dim=1).unsqueeze(-1)                      #   [B, L, h] -> [B, h, 1]\n",
    "\n",
    "        return forecast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(DeepNPTS, title_level=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(DeepNPTS.fit, name='DeepNPTS.fit', title_level=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(DeepNPTS.predict, name='DeepNPTS.predict', title_level=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "check_model(DeepNPTS, [\"airpassengers\"])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Usage Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| eval: false\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast import NeuralForecast\n",
    "from neuralforecast.models import DeepNPTS\n",
    "from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic\n",
    "\n",
    "Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]] # 132 train\n",
    "Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test\n",
    "\n",
    "nf = NeuralForecast(\n",
    "    models=[DeepNPTS(h=12,\n",
    "                   input_size=24,\n",
    "                   stat_exog_list=['airline1'],\n",
    "                   futr_exog_list=['trend'],\n",
    "                   max_steps=1000,\n",
    "                   val_check_steps=10,\n",
    "                   early_stop_patience_steps=3,\n",
    "                   scaler_type='robust',\n",
    "                   enable_progress_bar=True),\n",
    "    ],\n",
    "    freq='ME'\n",
    ")\n",
    "nf.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12)\n",
    "Y_hat_df = nf.predict(futr_df=Y_test_df)\n",
    "\n",
    "# Plot quantile predictions\n",
    "Y_hat_df = Y_hat_df.reset_index(drop=False).drop(columns=['unique_id','ds'])\n",
    "plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1)\n",
    "plot_df = pd.concat([Y_train_df, plot_df])\n",
    "\n",
    "plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1)\n",
    "plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True')\n",
    "plt.plot(plot_df['ds'], plot_df['DeepNPTS'], c='red', label='mean')\n",
    "plt.grid()\n",
    "plt.plot()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
